package cn.snowsoft.iot.module.cps.service.monitoring;


import cn.snowsoft.iot.framework.common.pojo.CommonResult;
import cn.snowsoft.iot.module.cps.controller.admin.monitoring.vo.SearchParamVO;
import cn.snowsoft.iot.module.cps.dal.dataobject.monitoring.Monitoring;
import cn.snowsoft.iot.module.cps.dal.mysql.monitoring.MonitoringMapper;
import cn.snowsoft.iot.module.cps.utils.DataUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.xxdb.data.BasicTable;
import com.xxdb.data.DolphinDBUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.IntStream;

/**
 * 数采监控
 */
@Service
@RequiredArgsConstructor
public class MonitoringServiceImpl extends ServiceImpl<MonitoringMapper, Monitoring> implements IMonitoringService {
	private final DolphinDBUtils dolphindbUtils;

	/**
	 * 今日 today，本周 Week，本月 month，开始到结束 dataChange
	 * @return 时序数据库查询结果
	 */
	@Override
	public CommonResult cardDate(SearchParamVO searchParamVO) throws IOException {
		return CommonResult.success(cardHistory(searchParamVO));
	}
	@Override
	public CommonResult selectDataHistoryStatistic(SearchParamVO searchParamVO) throws IOException {
		return CommonResult.success(historyStatistic(searchParamVO));
	}


	public Map<String, Object> historyStatistic(SearchParamVO searchParamVO) throws IOException {
		SimpleDateFormat sf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
		Map<String, Object> result = new HashMap();
		// 执行时序数据库脚本进行查询测定
		BasicTable data = dolphindbUtils.searchHistoryStatistic(searchParamVO.getDeviceCode(), searchParamVO.getPointCode(), sf.format(searchParamVO.getBeginDate()), sf.format(searchParamVO.getEndDate()));
		//发生错误时处理
		if (StringUtils.isEmpty(data)) {
			result.put("currentValue","0");
			result.put("avgValue", "0");
			result.put("maxValue","0" );
			result.put("minValue","0");
			result.put("maxDiff","0");
			return result;
		}

		int rows = data.rows();

		IntStream.range(0, rows).forEach(index -> {
			String rowJson = data.getRowJson(index);
			JSONObject o = JSON.parseObject(rowJson);
			result.put("currentValue",o.getString("lastValue") == null ? "0" : new BigDecimal(o.getString("lastValue")).setScale(2, BigDecimal.ROUND_HALF_UP));
			result.put("avgValue",o.getString("avgValue") == null ? "0" : new BigDecimal(o.getString("avgValue")).setScale(2, BigDecimal.ROUND_HALF_UP));
			result.put("maxValue",o.getString("maxValue") == null ? "0" : new BigDecimal(o.getString("maxValue")).setScale(2, BigDecimal.ROUND_HALF_UP));
			result.put("minValue",o.getString("minValue") == null ? "0" : new BigDecimal(o.getString("minValue")).setScale(2, BigDecimal.ROUND_HALF_UP));
			result.put("maxDiff",o.getString("maxDiff") == null ? "0" : new BigDecimal(o.getString("maxDiff")).setScale(2, BigDecimal.ROUND_HALF_UP));

		});
		return result;
	}


	/**
	 * cardDate调用  exportCard 导出历史数据调用
	 * @return 时序数据库查询结果
	 */
	public Map<String, List> cardHistory(SearchParamVO searchParamVO) throws IOException {
		SimpleDateFormat sf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");

		// 执行时序数据库脚本进行查询测定
		BasicTable data = dolphindbUtils.searchHistoryData(searchParamVO.getDeviceCode(), searchParamVO.getPointCode(), sf.format(searchParamVO.getBeginDate()), sf.format(searchParamVO.getEndDate()));
		if (StringUtils.isEmpty(data)) {
			return null;
		}
		Map<String, List> result = new HashMap();
		List<String> xdata = new ArrayList<>();
		List<String> ydata = new ArrayList<>();
		String columnName = searchParamVO.getPointCode();
		int rows = data.rows();
		IntStream.range(0, rows).forEach(index -> {
			String rowJson = data.getRowJson(index);
			JSONObject o = JSON.parseObject(rowJson);
			try {
				SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd'T'HH:mm:ss.SSS");
				Date thetime = format.parse(o.getString("thetime"));
				format.applyPattern("yyyy.MM.dd HH:mm:ss");
				String formattedTime = format.format(thetime);
				xdata.add(formattedTime);
				ydata.add(o.getString(columnName));
			} catch (ParseException e) {
				log.warn("历史数据查询，构造数据结构失败");
				throw new RuntimeException(e);
			}
		});
		result.put("xdata", xdata);
		result.put("ydata", ydata);
		return result;
	}

}
